import {reqAddCart} from  '../../../api/service'
import {reqGoodsDetail} from  '../../../api/index'
Page({
  data: {
    show:false,
    id:'',
    picUrls:[],
    banner:{},
    brandInfo:{},
    name:'',
    comments:[],
    detailHtml:'',
    commentsCount:0,
    counterPrice:0,
    showBuyStatus:false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    this.setData({id:options.id})
  },
  onShow(){
    this.getGoodDetail()
  },
  showPop(){
    this.setData({
      show:true
    })
  },
  onClose(){
    this.setData({
      show:false
    })
  },
  // 加入购物车
  async addCart(){
    if(wx.getStorageSync('token')){
      try {
        const res = await reqAddCart()
        if(res.code === 200){
          wx.showToast({
            title: '添加购物车成功',
            icon:'success'
          })
        }
      } catch (error) {
        console.log(error)
      }
    }else{
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  
  },
  // 获取商品详情
  async getGoodDetail(){
    try {
      const res = await reqGoodsDetail(this.data.id)
      console.log(res)
      const {banner,brandInfo,name,comments,counterPrice} = res.item
      const itemDetail = res.item.itemDetail
      let picUrls = []
      for(const key in itemDetail){
        if(key.startsWith('pic')){
          console.log(key)
          console.log(itemDetail)
          picUrls.push(itemDetail[key])
        }
      }
      this.setData({banner,brandInfo,itemDetail,name,comments,picUrls,counterPrice,commentsCount:res.commentsCount})
    } catch (error) {
      console.log(error)
      wx.showToast({
        title: '获取详情失败',
        icon:'error'
      })
    }
  },
  // 展示购物车
  showBuy(){
    if(wx.getStorageSync('token')){
      this.setData({
        showBuyStatus:true
      })
    }else{
      wx.navigateTo({
        url:'/pages/login/login'
      })
    }
  
  }
})